//
//  HRVDetailModel.swift
//  DaFit
//
//  Created by 尹琼 on 2022/6/11.
//  Copyright © 2022 sylar. All rights reserved.
//

import UIKit
import MYModule
import HandyJSON

import RxSwift
import RxCocoa

open class HRVProvider: NSObject {
    
    public var date: Date
    
    public let curDayChart = BehaviorRelay<HRVChartDataModel?>(value: nil)

    public let weekChart = BehaviorRelay<HRVChartDataModel?>(value: nil)

    public let monthChart = BehaviorRelay<HRVChartDataModel?>(value: nil)
    
    
    public init(date: Date) {
        self.date = date
        super.init()
        
        addNotifation()
        
        updateData()
        
        updateTimingHRVDate()
    }
    
    func addNotifation() {
        
        /// 进入前台通知,延时一秒是因为给SDK setTime 留时间
        NotificationCenter.default.rx.notification(UIApplication.willEnterForegroundNotification).take(until: self.rx.deallocated).delay(.seconds(1), scheduler: MainScheduler()).subscribe(onNext: {[weak self] noti in
            
            guard let self = self else { return }
            let nowTime = Date().timeIntervalSince1970
            let time = self.date.timeIntervalSince1970
            // 半小时时差,就需要更新
            if abs(nowTime - time) >= 1800 {
                self.updateData()
            }
            
        }).disposed(by: rx.disposeBag)
        
        
        NotificationCenter.default.rx.notification(.kUpdateUINotification).take(until: self.rx.deallocated).subscribe(onNext: {[weak self] _ in
            
            self?.updateData()
            
        }).disposed(by: rx.disposeBag)
        
    }

    public func updateData() {
        
        getDayDatas()
        getWeekDatas()
        getMonthDatas()
        
    }
    
    public func updateTimingHRVDate() {
        
        
        if !date.isToday {
            return
        }
        
        BluetoothManager.shared.getTimingHRVs(of: self.date, backward: 15, forcedUpdate: false) {[weak self] in
            
            self?.updateData()
            
        }
        
    }
    
    
    public func getDayDatas() {
        
        let hrvModel = HRVModel.day(date: date) ?? HRVModel()
        hrvModel.date = date
        let model = HRVChartDataModel(date: date, hrvModel: hrvModel)
        self.curDayChart.accept(model)
        
    }

    public func getWeekDatas() {

        let weekHRVs = HRVModel.weekDay(date: date)
        let weekModel = HRVChartDataModel(date: date, hrvModels: weekHRVs)
        weekChart.accept(weekModel)
    }

    public func getMonthDatas() {
        
        let monthHRVs = HRVModel.month(date: date)
        let monthModel = HRVChartDataModel(date: date, hrvModels: monthHRVs)
        
        monthChart.accept(monthModel)
    }
}


